package com.xiaoxie.system.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author xiaoxie
 * @create 2025-01-20 16:06
 * @Version 1.0
 * @Description: SaToken配置
 */
@Configuration
public class SaTokenConfig {

    @Bean
    public SaInterceptor getSaInterceptor() {
        return new SaInterceptor(handler -> {
            // 路由规则指定 登录校验
            SaRouter.match("/**")
                    .notMatch("/system/user/login",
                            "/test/**",
                            "/doc.html",                 // Knife4j 增强文档
                            "/webjars/**",               // Knife4j 前端资源
                            "/v3/api-docs/**",           // OpenAPI 描述文件
                            "/swagger-ui/**",            // 原生 Swagger UI
                            "/swagger-ui.html" )         // 原生 Swagger UI
                    .check(StpUtil::checkLogin);
        });
    }

    /**
     * 注册拦截器
     * @param saInterceptor
     * @return
     */
    @Bean
    public WebMvcConfigurer getWebMvcConfigurer(SaInterceptor saInterceptor) {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(saInterceptor)
                        .addPathPatterns("/**");
            }

            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:8080",
                                "http://localhost:8081")
                        .allowedMethods("*")
                        .allowCredentials(true);
            }
        };
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:8081");  // 允许所有来源，生产环境建议指定具体域名
        config.addAllowedOrigin("http://localhost:8080");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

}
